from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_cors import CORS
from toutiao.settings import config_dict,setup_log


app = Flask(__name__)

# 只需要修改 字典的key 就可以获取到指定的配置类
Config=config_dict['dev']
#设置日志
setup_log(Config)

#加载配置类
app.config.from_object(Config)

#创建 SQLAlchemy 实例
db=SQLAlchemy(app)

#创建一个redis实例
app.redis_store=redis.Redis(host=Config.REDIS_HOST,port=Config.REDIS_PORT)


# 设置跨域请求
CORS(app)

# 雪花算法生成id  能够确保唯一
from snowflake.id_worker import IdWorker
app.id_worker = IdWorker(datacenter_id=Config.DATACENTER_ID,
                        worker_id=Config.WORKER_ID,
                        sequence=Config.SEQUENCE)

# 在这里注册蓝图
from toutiao.apps.home import home_blueprint
app.register_blueprint(home_blueprint)

from toutiao.apps.user import user_blueprint
app.register_blueprint(user_blueprint)

# 获取token中用户信息
from flask import request, g
from auth.auth_jwt import verify_token
@app.before_request
def before_request():
    # 初始化变量
    g.user_id = None
    g.is_refresh_token = None

    # 在每次请求之前都要判断一下请求头中是否存在token信息
    authorization = request.headers.get('Authorization')
    # 请求头中有信息并且数据是以Bearer为前缀
    if authorization and authorization.startswith('Bearer'):
        # Bearer xxxx.xxxx.xxx  格式
        # 要获取token
        token = authorization[7:]
        # 验证token
        payload = verify_token(token)
        if payload:
            g.user_id = payload.get('user_id')
            g.is_refresh_token = payload.get('refresh')


















